// Copyright (c) 2007-2008 Simon Fell
//
// Permission is hereby granted, free of charge, to any person obtaining a 
// copy of this software and associated documentation files (the "Software"), 
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the 
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included 
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
// THE SOFTWARE.
//

#import "SalesforceFileSystem.h"
#import "zkSforceClient.h"
#import "zkSObject.h"
#import "zkUserInfo.h"
#import "File.h"
#import "Folder.h"
#import "Preferences.h"
#import "zkSoapException.h"

@implementation SalesforceFileSystem

-(id)initWithSforceClient:(ZKSforceClient *)sf {
	self = [super init];
	clientPool = [[Pool alloc] initWithMaster:sf maxPoolItems:5];
	dataMru = [[Mru alloc] init];
	root = [[RootFolder alloc] initWithName:@"/" id:[[sf currentUserInfo] userId] modstamp:[NSDate date] created:[NSDate date] clientPool:clientPool];
	return self;
}

-(void)dealloc {
	[clientPool release];
	[dataMru release];
	[root release];
	[super dealloc];
}

- (FileSystemItem *)fsItemForPath:(NSString *)path {
	if ([path isEqualToString:@"/"])
		return root;
	// eat the leading /
	path = [path substringFromIndex:1];
	// now, if there's a / in it, then it must be directory/file.foo otherwise, its just a directory
	NSArray *pathParts = [path componentsSeparatedByString:@"/"];
	Folder *theFolder = (Folder*)[root fileWithName:[pathParts objectAtIndex:0]];
	if ([pathParts count] == 1 || theFolder == nil)
		return theFolder;

	return [theFolder fileWithName:[pathParts objectAtIndex:1]];
}

// delegate methods

- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path 
                                 error:(NSError **)error {
    return [((Folder*)[self fsItemForPath:path]) filenames];
}

- (NSDictionary *)attributesOfItemAtPath:(NSString *)path 
								userData:(id)userData
								   error:(NSError **)error {
    return [[self fsItemForPath:path] attributes];
}	   

- (NSData *)contentsAtPath:(NSString *)path {
	FileSystemItem *fsi = [self fsItemForPath:path];
	if (fsi == nil) return nil;
	if ([fsi isKindOfClass:[File class]]) {
		File *f  = (File *)fsi;
		return [f fileBodyUsingMru:dataMru];
	}
	return nil;
}
@end
